package dao;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import core.base.page.Page;
import core.base.page.PageRequest;

public class MyBatisBaseDao extends SqlSessionDaoSupport {
	@Resource
	private SqlSessionFactory sessionFactoryTemp;

	public void setSessionFactoryTemp(SqlSessionFactory sessionFactoryTemp) {
		this.sessionFactoryTemp = sessionFactoryTemp;
	}

	@PostConstruct
	public void sessionFactory() {
		super.setSqlSessionFactory(sessionFactoryTemp);
	}
	
	public <T, P> Page<T> queryForPage(PageRequest<P> pageReq, String sqlname){
		return queryForPage(pageReq, sqlname, sqlname+"Count");
	}
	
	public <T, P> Page<T> queryForPage(PageRequest<P> pageReq, String sqlname, String countSqlname){
		P filter = pageReq.getFilters();
		String sortColumns = pageReq.getSortColumns();
		
		int startRow = pageReq.getStartRow();
		int endRow = pageReq.getEndRow();
		
		Map parameter = new HashMap();
		parameter.put("f", filter);
		parameter.put("startRow", startRow);
		parameter.put("endRow", endRow);
		parameter.put("sortColumns", sortColumns);
		
		Integer totalCount = (Integer)super.getSqlSessionTemplate().selectOne(countSqlname, parameter);
		Page<T> page = new Page<T>(pageReq, totalCount);
		List<T> list = super.getSqlSessionTemplate().selectList(sqlname, parameter);
		page.setResult(list);
		return page;
	}
	
}
